<script lang="tsx">
import { defineComponent, useSlots } from 'vue';
import { ElRow, ElCol } from 'element-plus';
import { merge } from 'lodash-es';
import { responsiveProps } from './types';

export default defineComponent({
  name: 'ResponsiveRow',
  props: responsiveProps,
  setup(props) {
    const slots = useSlots();
    return () => {
      const { col = {}, row = {} } = props;
      const childList = slots?.default?.() || [];
      // 默认参数
      const defaultColProps = { xs: 24, sm: 12, md: 8, lg: 8, xl: 6 };
      type TChild = typeof childList;
      const colChildList = [] as TChild;
      const deep = (nodes: TChild) => {
        if (Array.isArray(nodes)) {
          nodes.forEach((child) => {
            // 优先级：默认 < 父组件col < 子组件col
            const childCol = merge({}, defaultColProps, col, child.props?.col || {});

            const _type = child?.type as any;
            if (_type?.name === 'ElCol') {
              child.props = childCol;
              colChildList.push(child);
              return;
            }
            /**
             * 有children还是要处理
             */
            if (!_type?.name) {
              /**
               * _type在生产模式下，v-if的类型为 Symbol()
               * ps：若想控制显隐暂时先使用v-if，不建议使用v-show
               *    因为在dirs（数组）中没有能判断具体指令名称的属性
               */
              const vNodeType = Object(_type).toString();
              if (vNodeType === 'Symbol(v-fgt)' && child.children?.length) {
                deep(child.children as TChild);
                return;
              }
              if (vNodeType === 'Symbol(Comment)' || vNodeType === 'Symbol()') {
                return;
              }
            }
            colChildList.push(<ElCol {...childCol}>{child}</ElCol>);
          });
        }
      };
      deep(childList);
      return <ElRow {...row}>{colChildList}</ElRow>;
    };
  },
});
</script>
